//
// Created by 11510 on 2024/6/17.
//
#include <iostream>
using namespace std;

class Base{
public:
    virtual void print(){
        printf("parent\n");
    }

    long _base = 10;
};
class Derived: public Base{
public:
    long _derived = 101;
    void display(){
        printf("display %d\n", _derived);
    }
};

void test0(){
//    Derived derived;
//    cout << sizeof derived << endl;
//    cout << sizeof (Base) << endl;
    Base base;
    Derived derived;

    /* 可以用子类对象给父类赋值，不可用父类给子类赋值 */
    base = derived;
    /*derived = base;*/

}
void test1(){
    /* 可以用父类指针指向子类对象，不可用子类指针指向父类 */
    Base* base_ptr = new Derived();

    /* 可以用父类引用绑定子类对象，不能用子类引用绑定父类对象 */
    Derived derived;
    Base& ref1 = derived;

    ref1._base;
    /* 访问不了子类的成员 */
//    ref._derived;

    Base base;
    /* 访问越界，非法，*/
//    Derived ref2 = &base;
}

void test2(){
    Base base;
    Derived derived;

//    Base* basePtr = &derived;
    Base* basePtr = &base;
    Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);

    if(derivedPtr == nullptr){
        /* 转换失败，但是空指针可以访问不访问成员的函数 */
    }else{
        /* 转换成功 */
        derivedPtr->display();
    }


}


int main() {
    test2();
    return 0;
}
